package com.fablesoft.projectdatacollect.album;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.fablesoft.projectdatacollect.R;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 这个是显示一个文件夹里面的所有图片时的界面
 *
 * @author king
 * @QQ:595163260
 * @version 2014年10月18日 下午11:49:10
 */
public class ShowAllPhotoActivity extends Activity {
    //	private final static String TAG = "ShowAllPhotoActivity";
    private GridView gridView;
    private ProgressBar progressBar;
    private AlbumGridViewAdapter gridImageAdapter;
    //	public final static int SELECTED_FILE_FLAG = 0xf6;
    public static int maxCount = 10;
    public static ArrayList<ImageItem> tempSelectBitmap = null;   //选择的图片的临时列表
    // 完成按钮
    private Button okButton;
    // 预览按钮
    private View preview;
    // 返回按钮
    private LinearLayout back;
    private View switchFolder;
    private TextView switchFolderText;
    private TextView previewText;
    private ListView fileListView;
    private RelativeLayout rlFileListView;
    private Intent intent;
    private Context mContext;
    private ArrayList<ImageItem> dataList;
    private AlbumHelper helper;
    public List<ImageBucket> contentList;
    private String finishStr;
    private FolderAdapter folderAdapter;
    public static Activity activity;
    public String takePhotoUrl; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //		if(savedInstanceState != null){
        //			Log.i("luzx", "tempSelectBitmap");
        //			ShowAllPhotoActivity.maxCount = savedInstanceState.getInt("maxCount");
        //			ShowAllPhotoActivity.tempSelectBitmap = (ArrayList<ImageItem>) savedInstanceState.getSerializable("selectImages");
        //		}
        setContentView(R.layout.plugin_camera_show_all_photo);
        mContext = this;
        activity = this;
        tempSelectBitmap = new ArrayList<ImageItem>();
        back = (LinearLayout) findViewById(R.id.showallphoto_back);
        preview = findViewById(R.id.show_photo_preview);
        previewText = (TextView)findViewById(R.id.show_photo_preview_text);
        okButton = (Button) findViewById(R.id.showallphoto_ok_button);
        switchFolder = findViewById(R.id.switch_image_folder);
        switchFolderText = (TextView)findViewById(R.id.switch_image_folder_text);
        fileListView = (ListView) findViewById(R.id.file_list_view);
        rlFileListView = (RelativeLayout) findViewById(R.id.rl_file_list_view);

        this.intent = getIntent();
        maxCount = intent.getIntExtra("count", maxCount);
        switchFolder.setOnClickListener(new SwitchListener());
        back.setOnClickListener(new BackListener());
        preview.setOnClickListener(new PreviewListener());
        init();
        initListener();
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 0:
                rlFileListView.setVisibility(View.GONE);
                break;
            case 1:
                gridImageAdapter.setDataList(dataList);
                gridView.setAdapter(gridImageAdapter);
                break;
            }
        }
    };

    private class SwitchListener implements OnClickListener {// 取消按钮的监听
        @Override
		public void onClick(View v) {
            if(folderAdapter == null){
                folderAdapter = new FolderAdapter(mContext, contentList);
                fileListView.setAdapter(folderAdapter);
                fileListView.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        dataList = (ArrayList<ImageItem>) contentList
                                .get(position).imageList;
                        String folderName = contentList.get(position).bucketName;
                        switchFolderText.setText(folderName);
                        gridImageAdapter.setDataList(dataList);
                        gridImageAdapter.notifyDataSetChanged();
                        folderAdapter.setSelectedFile(position);
                        folderAdapter.notifyDataSetChanged();
                        rlFileListView.setVisibility(View.GONE);
                    }
                });
            }
            if (rlFileListView.getVisibility() == View.VISIBLE) {
                hiddenFileList();
            } else {
                showFileList();
            }
        }
    }

    private TranslateAnimation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,     
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,     
            1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
    private TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,     
            0.0f, Animation.RELATIVE_TO_SELF, 0.0f,     
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,     
            1.0f);

    private void showFileList(){
        mShowAction.setDuration(300);
        rlFileListView.setVisibility(View.VISIBLE);
        fileListView.startAnimation(mShowAction);
    }

    private void hiddenFileList(){
        mHiddenAction.setDuration(300);
        fileListView.startAnimation(mHiddenAction);
        mHandler.sendEmptyMessageDelayed(0, 300);
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            isShowOkBt();
            gridImageAdapter.notifyDataSetChanged();
        }
    };

    private class PreviewListener implements OnClickListener {
        @Override
		public void onClick(View v) {
            if (tempSelectBitmap.size() > 0) {
                Intent i = new Intent(ShowAllPhotoActivity.this, GalleryActivity.class);
                startActivityForResult(i, 2);
            }
        }

    }

    private class BackListener implements OnClickListener {// 返回按钮监听

        @Override
		public void onClick(View v) {
            if(rlFileListView.getVisibility() == View.VISIBLE){
                hiddenFileList();
            }else{
                tempSelectBitmap.clear();
                tempSelectBitmap = null;
                ShowAllPhotoActivity.this.setResult(Activity.RESULT_CANCELED);
                finish();
            }
        }
    }

    private void init() {
        helper = AlbumHelper.getHelper();
        helper.init(getApplicationContext());
        new Thread(){
            @Override
			public void run() {
                contentList = helper.getImagesBucketList(true);
                if(contentList != null && contentList.size() > 0){
                    // 创建所有图片
                    String allImage = getResources().getString(R.string.all_photo);
                    if(allImage.equals(contentList.get(0).bucketName)){
                        dataList = (ArrayList<ImageItem>) contentList.get(0).imageList;
                    }else{
                        dataList = new ArrayList<ImageItem>();
                        ImageItem takePhoto = new ImageItem();
                        takePhoto.setTakePhoto(true);
                        dataList.add(takePhoto);
                        for (int i = 0; i < contentList.size(); i++) {
                            dataList.addAll(contentList.get(i).imageList);
                        }
                        if(dataList.size() > 0){
                            ImageBucket all = new ImageBucket();
                            all.bucketName = allImage;
                            all.count = dataList.size();
                            all.imageList = dataList;
                            contentList.add(0, all);
                        }
                    }
                }else{
                    dataList = new ArrayList<ImageItem>();
                    ImageItem takePhoto = new ImageItem();
                    takePhoto.setTakePhoto(true);
                    dataList.add(takePhoto);
                }

                mHandler.sendEmptyMessage(1);
            };
        }.start();


        IntentFilter filter = new IntentFilter("data.broadcast.action");
        registerReceiver(broadcastReceiver, filter);

        progressBar = (ProgressBar) findViewById(R.id.showallphoto_progressbar);
        progressBar.setVisibility(View.GONE);
        gridView = (GridView) findViewById(R.id.showallphoto_myGrid);
        gridImageAdapter = new AlbumGridViewAdapter(this);
        okButton = (Button) findViewById(R.id.showallphoto_ok_button);
        finishStr = getResources().getString(R.string.finish);
        isShowOkBt();
    }

    private void initListener() {
        gridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                View imageViewSelected = view.findViewById(R.id.image_view_selected);
                boolean isContains = false;
                int containsIndex = 0;
                for(int i=0; i<ShowAllPhotoActivity.tempSelectBitmap.size(); i++ ){
                    if(ShowAllPhotoActivity.tempSelectBitmap.get(i).getImagePath().equals(dataList.get(position).getImagePath())){
                        isContains = true;
                        containsIndex = i;
                        break;
                    }
                }
                if(isContains){
                    tempSelectBitmap.remove(containsIndex);
                    imageViewSelected.setVisibility(View.GONE);
                }else{
                    if(tempSelectBitmap.size() >= maxCount){
                        Toast.makeText(ShowAllPhotoActivity.this,
                                R.string.only_choose_num, Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        imageViewSelected.setVisibility(View.VISIBLE);
                        tempSelectBitmap.add(dataList.get(position));
                    }
                }
                okButton.setText(finishStr + "("
                        + tempSelectBitmap.size() + "/"
                        + maxCount + ")");
                isShowOkBt();
            }
        });

        okButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                okButton.setClickable(false);
                if(tempSelectBitmap.size() > 0){
                    ShowAllPhotoActivity.this.setResult(Activity.RESULT_OK);
                    finish();
                }
            }
        });
    }

    public void isShowOkBt() {
        if (tempSelectBitmap.size() > 0) {
            okButton.setText(finishStr + "(" + tempSelectBitmap.size()
                    + "/" + maxCount + ")");
            preview.setClickable(true);
            okButton.setClickable(true);
            preview.setEnabled(true);
            okButton.setEnabled(true);
            okButton.setTextColor(0xffffffff);
            previewText.setTextColor(0xffffffff);
        } else {
            okButton.setText(finishStr + "(" + tempSelectBitmap.size()
                    + "/" + maxCount + ")");
            preview.setClickable(false);
            okButton.setClickable(false);
            preview.setEnabled(false);
            okButton.setEnabled(false);
            okButton.setTextColor(0xff6a6c6e);
            previewText.setTextColor(0xff6a6c6e);
        }
    }

    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(rlFileListView.getVisibility() == View.VISIBLE){
                hiddenFileList();
            }else{
                tempSelectBitmap.clear();
                tempSelectBitmap = null;
                ShowAllPhotoActivity.this.setResult(RESULT_CANCELED);
                this.finish();
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(broadcastReceiver);
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == Activity.RESULT_OK){
            sendBroadCastRemountSDcard(takePhotoUrl);
            Intent intent = new Intent(this, GalleryActivity.class);
            intent.putExtra("takePhoto", takePhotoUrl);
            startActivity(intent);
        }
    }

    private void sendBroadCastRemountSDcard(String filePath) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File file = new File(filePath);
        intent.setData(Uri.fromFile(file));
        mContext.sendBroadcast(intent);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        //		super.onRestoreInstanceState(savedInstanceState);
        //		ShowAllPhotoActivity.this.setResult(-2);
        finish();
    }

    //	@Override
    //	protected void postRequest() throws Throwable {
    //		Processor proc = new Processor(getApp().getSSID());
    //		FileResponse response = proc.uploadImage(ShowAllPhotoActivity.tempSelectBitmap, objecttype);
    //    	ShowAllPhotoActivity.tempSelectBitmap.clear();
    //    	receiveResponse(new Result(Result.SUCCESS, ""), response);
    //	}
}
